<template>
  <div id="logi">
  <AppHeader/>


    <div style="width: 100%;">

      <div style="margin: 0 auto; height: 800px; width: 1700px; display: flex;">
        <div style="width: 1000px;">
          <div style="width: 1000px; height: 400px;">
            <el-carousel :interval="4000" type="card" height="600px" indicator-position="none"
              @change="handleCarouselChange">
              <el-carousel-item v-for="img in goodsImage" :key="img.imageUrl"
                style="box-shadow: 0 4px 6px rgba(0,0,0,0.1), 0 1px 3px rgba(0,0,0,0.06);">
                <img :src="img.imageUrl" alt="商品图片" style="width: 500px; height: 600px;">
              </el-carousel-item>
            </el-carousel>
          </div>

          <!-- 自定义指示器 -->
          <div class="custom-indicators">
            <div v-for="item in 4" :key="item" :class="['indicator', { active: activeIndex === item - 1 }]"
              @click="goTo(item - 1)"></div>
          </div>
        </div>
        <div
          style=" width: 700px; margin-left: 30px; background: #fff; padding: 40px; border-radius: 12px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);;">
          <el-main>
            <div style="margin: 10px auto;  width: 400px; height: 100px;line-height: 100px;font-size: 40px;">
              欢迎来到xxx商城管理系统，请登录OwO
            </div>


            <div id="logininfo">
              <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="账户名" prop="phone">
                  <el-input v-model="ruleForm.phone" style="height: 40px; width: 420px;"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" style="margin-top: 40px;">
                  <el-input v-model="ruleForm.password" style="height: 40px; width: 420px;"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="verifiCode">
                  <div style="display: flex; align-items: center;">
                    <!-- 输入验证码 -->
                    <el-input v-model="ruleForm.verifiCode" placeholder="请输入验证码"
                      style="height: 40px; width: 90px; margin-right: 10px;" />
                    <img :src="verificationCode.codeImg" alt="验证码" style="width: 100px; height: 40px; cursor: pointer;"
                      @click="getverificationCode" />

                  </div>
                  <div style="width: 100px; height: 40px; margin: 0,auto;">
                    <el-checkbox v-model="ruleForm.rememberMe" style="margin: 0,0,0,20px;">记住我</el-checkbox>
                  </div>
                </el-form-item>
                <div style="margin: 50px 60px 0 -30px; display: flex ;flex-direction:row ; width: 450px;">
                  <el-form-item>
                    <el-button style="width: 100px;" type="primary" @click="submitForm('ruleForm')">立即登录</el-button>
                    <el-button style="width: 100px;" @click="resetForm('ruleForm')">重置</el-button>
                    <el-button style="width: 100px;" type="primary" @click="register()">前往注册</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </div>

          </el-main>
        </div>
      </div>

    </div>

    <!-- <div id="footer"></div> -->

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import api from "@/api/api";
import { ElLoading, ElMessage } from 'element-plus'//引入element-plus的JS服务
import Cookies from "js-cookie";//引入cookie用于存储账号密码
import { decrypt, encrypt } from "../Tools/jsencrypt"
import AppHeader from '@/components/Header/AppHeader.vue'//引入头部组件
// 创建响应数据存储对象
const goodsImage = ref([])
const verificationCode = ref([])

const getverificationCode = async () => {
  try {
    //获取验证码
    const verificationCodeResponse = await api.get("user/verificationCode", { noAuth: true })

    verificationCode.value = verificationCodeResponse.data
  } catch (error) {
    console.error('获取失败:', error)
  }
}

const getgoodsImage = async () => {
  try {
    //从后端拿到调用数据
    //获取轮播图
    const ImagesResponse = await api.get("goods/GetRandomImages", { noAuth: true })
    //测试后端数据
    // console.log(ImagesResponse.data)

    //模拟数据
    // const ImagesResponse = [
    //   { product_id: 6, image_url: "//img11.360buyimg.com/n1/s450x450_jfs/t1/199502/17/49615/51176/674579acF81f02cb6/c0322a4876c4fc09.png" },
    //   { product_id: 6, image_url: "//img11.360buyimg.com/n1/s450x450_jfs/t1/271066/37/15197/51701/67ecd969Fcc8bee51/5b3e52f7af538cb2.jpg.avif" },
    //   { product_id: 6, image_url: "//img13.360buyimg.com/n1/s450x450_jfs/t1/270532/6/5124/44509/67d79dc8F1636e0a8/225a03b972ab22bf.jpg.avif" }
    // ]
    // goodsImage.value = ImagesResponse


    // 将获取到的数据赋值给响应式变量
    goodsImage.value = ImagesResponse.data

  } catch (error) {
    console.error('获取商品数据失败:', error)
  }
}


// 路由和 Vuex store
const router = useRouter()
const store = useStore()

// 表单引用（用于校验/重置）
const ruleFormRef = ref(null)

// 表单数据
const ruleForm = reactive({
  phone: '',
  password: '',
  verifiCode: '',
  rememberMe: true,
})

// 组件加载时自动执行 fetchGoods
onMounted(() => {
  getgoodsImage(),
    getverificationCode()
})
// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入账户名', trigger: 'blur' },
    { min: 11, max: 11, message: '长度为 11 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
  ],
  verifiCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '请输入图片中的 4 个字符', trigger: 'blur' }
  ],
  rememberMe: []
}


// 轮播图索引
const activeIndex = ref(0)

// 加载状态
// const loading = ref(false)

// 提交表单方法
const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    //调试验证码
    // console.log("用户输入" + ruleForm.verifiCode)
    // console.log("后端对象" + verificationCode.value)
    // console.log("后端正确的" + verificationCode.value.verifiCode)
    if (valid) {
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (ruleForm.rememberMe) {
        Cookies.set("phone", ruleForm.phone, { expires: 30 });
        Cookies.set("password", encrypt(ruleForm.password), { expires: 30 });
        Cookies.set("rememberMe", ruleForm.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("phone");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 验证码校验
      if (ruleForm.verifiCode !== verificationCode.value.verifiCode) {
        ElMessage.error('验证码不正确，请重新输入')
        return
      }
      login()
    } else {
      ElMessage.error('请检查表单填写是否正确！')
    }
  })
}

// 登录逻辑
const login = async () => {
  // loading.value = true
  const loadingInstance = ElLoading.service({
    lock: true,                  // 锁住页面
    text: '登录中，请稍候...',     // 显示的文字
    background: 'rgba(0, 0, 0, 0.3)',  // 背景半透明
  })
  try {
    const startTime = Date.now()//创建加载时间对象

    const duration = Date.now() - startTime

    const minDisplayTime = 1000  // 最少展示 500ms
    //优化加载显示，使加载时间至少500ms，多了再加
    if (duration < minDisplayTime) {
      await new Promise(resolve => setTimeout(resolve, minDisplayTime - duration))
    }

    // console.log("传回后端的" + JSON.stringify(ruleForm));

    const response = await api.post('/user/login', ruleForm)
    if (response.data.code === 20200) {
      // 登录成功，保存用户信息并跳转页面
      const userInfo = response.data.data
      const token = response.data.token
      store.dispatch('user/setUserInfo', { userInfo, token })
      // console.log('登录成功', response.data)
      router.push('/SecuritySetting')
    } else {
      console.log('登录失败', response.data)
      ElMessage.error('登录失败，请检查账号密码')
    }
  } catch (error) {
    console.log('登录异常', error)
    router.push('/404')
  } finally {
    // loading.value = false
    // 4. 关闭 loading
    loadingInstance.close()
  }
}

// 重置表单
const resetForm = () => {
  ruleFormRef.value.resetFields()
}

// 注册跳转
const register = () => {
  router.push('/ShopRegister')
}

// 切换轮播图索引
const handleCarouselChange = (index) => {
  activeIndex.value = index
}

// 跳转到指定轮播图页
const goTo = (index) => {
  activeIndex.value = index
}

//加载cookie中的信息
function getCookie() {
  const phone = Cookies.get("phone");
  const password = Cookies.get("password");
  const rememberMeFromCookie = Cookies.get("rememberMe");
  if (phone !== undefined) {
    ruleForm.phone = phone;
  }
  if (password !== undefined) {
    ruleForm.password = decrypt(password);
  }
  ruleForm.rememberMe = rememberMeFromCookie === 'true';
}

getCookie();
</script>

<style scoped>
#header {
  height: 100px;
  background-color: rgb(255, 174, 0);
}

/* #footer {
  height: 200px;
  margin-bottom: 0%;
  position: absolute;
  bottom: 0;
  width: 100%;
} */

.headerinfo {
  right: 50px;
  margin-right: 5%;
  height: 100px;
  line-height: 100px;
  font-size: 20px;
}

.headerinfo a {
  text-decoration: none;
}

#logininfo {
  margin: 110px auto 10px auto;
  width: 400px;
  height: 300px;
}

#logo {
  margin-left: 100px;
  height: 100px;
  width: 150px;
}

#logo img {
  width: 100%;
  height: 100%;
}


.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 700px;
}


.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  line-height: 700px;
}



.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

.custom-indicators {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}

.indicator {
  width: 300px;
  background-color: #999;
  margin: 0 5px;
  cursor: pointer;
  border-radius: 2px;
  transition: background-color 0.3s;
}

.indicator.active {
  background-color: #409EFF;
}
</style>